package com.eis.function.in.base;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import com.eis.persist.dao.FunctionDAO;
import com.eis.persist.dao.impl.FunctionDAOImpl;
import com.eis.persist.model.function.PersistDataFetchSync;


public abstract class BaseTask implements EisTimerTask {
	protected static String currentRunnerId;
	private static final Logger logger = LoggerFactory.getLogger(BaseTask.class);
	protected JdbcTemplate dataSource;
	private int runduration;
	private int faultUpdateTimeout;
	
	public void setRunduration(int runduration) {
		this.runduration = runduration;
	}

	public void setFaultUpdateTimeout(int faultUpdateTimeout) {
		this.faultUpdateTimeout = faultUpdateTimeout;
	}



	static {
		// get local IP
		String localIp = "";
		try {
			localIp = InetAddress.getLocalHost().getHostAddress();
			localIp = localIp.replaceAll("\\.", "");
		} catch (UnknownHostException e) {
			logger.error("", e);
			// user a random string instead
			localIp = getRandomString(12);
		}
		
		// get current time
		Date current = new Date();
		DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
		String timeStr = df.format(current);
		
		// random number
		int radomnumber = new Random().nextInt(99999);
		
		// generate id
		currentRunnerId = localIp + timeStr + radomnumber;
	}
	
	private static String getRandomString(int length) {   
        String base = "0123456789";   
        Random random = new Random();   
        StringBuffer sb = new StringBuffer();   
        for (int i = 0; i < length; i++) {   
            int number = random.nextInt(base.length());   
            sb.append(base.charAt(number));   
        }   
        return sb.toString();   
    }   
	
	public void startTask() {
		// check if there is another runner running
		FunctionDAO functionDao = new FunctionDAOImpl(dataSource);
		PersistDataFetchSync persistDataFetchSync = functionDao.getPersistDataFetchSync(currentRunnerId, runduration, faultUpdateTimeout);
		if (persistDataFetchSync.getCurrentRunnerId().equals(currentRunnerId)) {
			runTask();
		}
	}
	

	@Override
	public void setDataSource(JdbcTemplate dataSource) {
		this.dataSource = dataSource;
	}

}
